package com.example.robertluozizhao.framecollectdemo.fragment;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.robertluozizhao.framecollectdemo.R;
import com.example.robertluozizhao.framecollectdemo.fragment.impl.FragmentNestImp;

import java.util.Stack;

/**
 * Created by Lzz on 4/25/2019.
 */

public abstract class BaseFragment extends Fragment implements FragmentNestImp.TextFragmentManagerContract{
    protected FragmentNestImp.TextFragmentManagerContract mFragmentManagerContract;
    protected Stack<Fragment> mFragmentsStack = new Stack<>();//用于fragment 嵌套管理


    public void setFragmentManagerContract(FragmentNestImp.TextFragmentManagerContract fragmentManagerContract) {
        mFragmentManagerContract = fragmentManagerContract;
    }

    @Override
    public void showFragment(BaseFragment fragment) {
        int fragmentGroupId = getFragmentGroupId();
        if (fragmentGroupId==-1) {
            return;
        }
        FragmentManager childFragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = childFragmentManager.beginTransaction();
        if (mFragmentsStack.size() > 0) {
            transaction.hide(mFragmentsStack.peek());
        }
        transaction.setCustomAnimations(R.anim.anim_activity_enter,
                R.anim.anim_activity_out,R.anim.anim_activity_out,R.anim.anim_activity_out);
        transaction.add(fragmentGroupId, fragment, fragment.getClass().getSimpleName());
        transaction.show(fragment);
        transaction.addToBackStack(null);
        transaction.commitAllowingStateLoss();
        if (!mFragmentsStack.contains(fragment)) {
            mFragmentsStack.push(fragment);
        }
        fragment.setFragmentManagerContract(this);
    }

    @Override
    public void backLastFragment() {
        if (mFragmentsStack != null && mFragmentsStack.size() > 1) {
            Fragment pop = mFragmentsStack.pop();
            FragmentManager childFragmentManager = getChildFragmentManager();
            FragmentTransaction transaction = childFragmentManager.beginTransaction();
            transaction.setCustomAnimations(R.anim.anim_activity_enter,
                    R.anim.anim_activity_out,R.anim.anim_activity_out,R.anim.anim_activity_out);
            transaction.remove(pop);
            Fragment peek = mFragmentsStack.peek();
            transaction.show(peek);
            transaction.commitAllowingStateLoss();
        }
    }

    public int getFragmentGroupId() {
        return -1;
    }
}
